#include "s3c2440_soc.h"
#include "uart.h"

void uart0_init()
{
	/* 配置GPH口为串口模式  */
	GPHCON &= ~((3<<4) | (3<<6));	// & 与清0
	GPHCON |=  ((2<<4) | (2<<6));	// | 或置1

	GPHUP  &= ~((1<<2) | (1<<3));
	/* 配置波特率
	 * UBRDIVn = (int)( UART clock / ( buad rate x 16) ) –1
	 * UART clock = 50MHz，这里要配置下，指定使用PCLK，查看手册配置UART CONTROL REGISTER
	 * UBRDIVn = (int)( 50000000 / ( 115200 x 16) ) –1 = 26
	 */

	UCON0 = 0x00000005;	/* 设置 PCLK Interrupt request or polling mode*/
	UBRDIV0 = 26;

	/* 配置串口模式 8n1*/
	ULCON0 = 0x00000003;

	/* 其他配置 */
}

int getchar(void)
{
	/* 判断这个状态寄存器是否接收满了，The buffer register has a received data
	 * 接收满了就返回URXH0这个寄存器数据
	 */
	while(!(UTRSTAT0 & (1<<0)));
	return URXH0;
}

int putchar(int c)
{
	/* 判断这个状态寄存器是否发送空了，Transmitter (transmit buffer & shifter register) empty
	 * 空了之后，就往这个UTXH0寄存器写入数据
	 */
	while(!(UTRSTAT0 & (1<<2)));
	UTXH0 = (unsigned char)c;
	return 0;
}

int puts(const char *s)
{
	while(*s)
	{
		putchar(*s);
		s++;
	}
	return 0;
}


/* 0xABCDEF12 */
void printHex(unsigned int val)
{
	int i;
	unsigned int arr[8];

	/* 先取出每一位的值 */
	for (i = 0; i < 8; i++)
	{
		arr[i] = val & 0xf;
		val >>= 4;   /* arr[0] = 2, arr[1] = 1, arr[2] = 0xF */
	}

	/* 打印 */
	puts("0x");
	for (i = 7; i >=0; i--)
	{
		if (arr[i] >= 0 && arr[i] <= 9)
			putchar(arr[i] + '0');
		else if(arr[i] >= 0xA && arr[i] <= 0xF)
			putchar(arr[i] - 0xA + 'A');
	}
}

void print1(void)
{
	puts("abc\n\r");
}

void print2(void)
{
	puts("123\n\r");
}

void printSWIVal(unsigned int *pSWI)
{
	puts("SWI val = ");
	printHex(*pSWI & ~0xff000000);
	puts("\n\r");
}
